package com.chen.gcode.utils;

import org.apache.batik.anim.dom.SAXSVGDocumentFactory;
import org.apache.batik.anim.dom.SVGOMSVGElement;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.StringWriter;
import java.net.URI;

public class SVGUtil {

    public static void main(String[] args) {
        try {
            analysisofSVG("/Users/king/Downloads/a.svg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 解析svg
    public static String analysisofSVG(String URI) throws Exception {
        File file = new File(URI);//svg url
        String parser = XMLResourceDescriptor.getXMLParserClassName();
        SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
        Document doc = f.createDocument(file.toURI().toString());


        //获取svg 标签得Id
        SVGOMSVGElement element = (SVGOMSVGElement)doc.getDocumentElement();
        NodeList pathNodes = element.getElementsByTagName("path");
        int pathNodeCount = pathNodes.getLength();

        for( int iPathNode = 0; iPathNode < pathNodeCount; iPathNode++ ) {
            MetaPostPath mpp = new MetaPostPath( pathNodes.item( iPathNode ) );
            System.out.println( mpp.toCode() );
        }

        String elementStr = TransformationSVG(element);
//        System.out.println(elementStr);
        return elementStr;
    }

    // 将标签转换成字符串
    public static String TransformationSVG(Element element) {

        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = null;
        try {
            transformer = transFactory.newTransformer();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
        StringWriter buffer = new StringWriter();
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes");
        try {
            transformer.transform(new DOMSource(element), new StreamResult(buffer));
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        String elementStr = buffer.toString();
        System.out.println("svg 所有标签"+elementStr);
        return elementStr;

    }

}
